<template>
  <div class="content-wraper">
    <el-row class="content">
      <el-col :span="6" class="content-left">
        <!-- <el-button type="primary" size="mini" icon="el-icon-plus" @click="showDirectoryMange=true;">机械目录管理</el-button> -->
        <div class="btns">
          <el-button type="primary" @click="editDir">机械目录编辑</el-button>
          <el-button type="primary" @click="delDir">机械目录删除</el-button>
        </div>
        <tree-box
          v-model="selectedNode"
          :data="treeData"
          title="机械目录"
          :no-search="true"
        />
      </el-col>
      <el-col :span="18" class="content-right">
        <div class="btns">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="addConsumableLedger"
          >新增</el-button>
          <el-button
            type="success"
            icon="el-icon-upload2"

            :loading="uploading"
            @click="importFile()"
          >导入</el-button>
          <el-button
            type="warning"
            icon="el-icon-download"
            @click="downloadFile()"
          >模板下载</el-button>
          <input
            ref="uploadELe"
            type="file"
            style="display: none"
            @change="fileChange($event)"
          >
          <!-- <el-button type="success" size="mini" icon="el-icon-edit" @click="editConsumableLedger">修改</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="delConsumableLedger">删除</el-button> -->
        </div>
        <div class="detail">
          <com-table
            :data="tableData"
            :columns="columns"
            :total="total"
            @pageChange="pageChange"
          >
            <template v-slot:name="{ row }">
              <a class="com-link" @click="viewDetail(row)">{{ row.name }}</a>
            </template>
            <template v-slot:options="{ row }">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editConsumableLedger(row)"
              >编辑</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="delConsumableLedger(row)"
              >删除</el-button>
            </template>
            <template v-slot:devStatus="{ row: { devStatus } }">
              {{ getDictName(consumableLedgerDevStatus, devStatus) }}
            </template>
            <template v-slot:devSource="{ row: { devSource } }">
              {{ getDictName(consumableLedgerDevSource, devSource) }}
            </template>
            <template v-slot:techStatus="{ row: { techStatus } }">
              {{ getDictName(consumableLedgerTechStatus, techStatus) }}
            </template>
            <template v-slot:factoryTime="{ row: { factoryTime } }">
              {{ dateFormat(factoryTime) }}
            </template>
            <template v-slot:payTime="{ row: { payTime } }">
              {{ dateFormat(payTime) }}
            </template>
            <template v-slot:monitorDevice="{ row: { monitorDevice } }">
              {{ getDictName(consumableLedgerMonitorDevice, monitorDevice) }}
            </template>
            <template v-slot:specialDevice="{ row: { specialDevice } }">
              {{ getDictName(consumableLedgerSpecialDevice, specialDevice) }}
            </template>
            <template v-slot:professionalDevice="{ row: { professionalDevice } }">
              {{ getDictName(consumableLedgerProfessionalDevice, professionalDevice) }}
            </template>
            <template v-slot:amTime="{ row: { amTime } }">
              {{ dateFormat(amTime) }}
            </template>
            <template v-slot:createTime="{ row: { createTime } }">
              {{ dateFormat(createTime) }}
            </template>
          </com-table>
        </div>
      </el-col>
    </el-row>
    <add-consumable-ledger
      :show-modal.sync="showModal"
      :opt-type="optType"
      :data="updateMaterialCodeObj"
      :treedata="selectedNode"
      @freshList="search"
    />
    <addMachineDir
      :tree-data="treeData"
      :show-modal.sync="showDirectoryMange"
      @freshTree="initTree"
    />
  </div>
</template>

<script>
// import addMachinery from './components/addMachinery.vue'
import { importMachineDeviceDetail } from '@/api/contractManage'
import { saveAs } from 'file-saver'

import addConsumableLedger from './components/addConsumableLedger.vue'
import { getDictName } from '@/utils/comm'
import moment from 'moment'
import {
  consumableLedgerDevStatus,
  consumableLedgerDevSource,
  consumableLedgerTechStatus,
  consumableLedgerMonitorDevice,
  consumableLedgerSpecialDevice,
  consumableLedgerProfessionalDevice
} from '@/utils/dicData'
import {
  // 目录模块
  addMachineDirectory,
  deleteMachineDirectory,
  // getMachineDirectoryDetail,
  // getMachineDirectoryList,
  getMachineDirectoryTree,
  // updateMachineDirectory,
  // 详情模块
  // addMachineDeviceDetail,
  deleteMachineDeviceDetail,
  // getMachineDeviceDetailDetail,
  getMachineDeviceDetailList
  // updateMachineDeviceDetail
} from '@/api/basicCode'
import addMachineDir from './addMachineDir.vue'

export default {
  name: 'MachineLibrary',
  components: {
    // addMachinery,
    addConsumableLedger,
    addMachineDir
  },
  data() {
    return {
      getDictName,
      consumableLedgerDevStatus,
      consumableLedgerDevSource,
      consumableLedgerTechStatus,
      consumableLedgerMonitorDevice,
      consumableLedgerSpecialDevice,
      consumableLedgerProfessionalDevice,

      directCurrentNode: null,
      showDirectoryMange: false,
      defaultProps: {
        children: 'nodes',
        label: 'name'
      },
      showAddMaterialDirect: false,
      addDirect: {},
      treeData: [], // 材料目录
      tableData: [], // 材料表格数据
      showAddMaterial: false, // 显示新增材料弹窗
      currentRow: null, // 当前表格选中行
      selectedNode: null, // 当前树结构选中行
      updateMaterialCodeObj: {}, // 表格单条材料体
      actionType: 1, // 1 新增材料 2更新材料
      defineWorkList: [], // 材料定义列表数据
      currentDefineWork: null, // 表格选中的单条材料定义
      uploading: false,
      saveLoading: false,
      disableImport: true,
      filterText: '',
      flowDetail: {},

      showDefineWorkList: false,
      optType: 'add',
      showModal: false,
      pageParams: {
        pageSize: 10,
        pageNum: 1
      },
      total: 0,
      columns: [
        {
          label: '序号',
          prop: 'sequence'
        },
        {
          label: '设备编号',
          prop: 'devNumber'
        },
        {
          label: '设备名称',
          prop: 'devName',
          width: '180'
        },
        {
          label: '设备分类',
          prop: 'devCategory',
          width: '100'
        },
        {
          label: '设备状态',
          prop: 'devStatus',
          slot: 'devStatus'
        },
        {
          label: '设备来源',
          prop: 'devSource',
          slot: 'devSource'
        },
        {
          label: '设备功率',
          prop: 'devPower'
        },
        {
          label: '规格',
          prop: 'specification'
        },
        {
          label: '所在地',
          prop: 'address'
        },
        {
          label: '资产编号',
          prop: 'assetNumber'
        },
        {
          label: '资产单位',
          prop: 'assetUnit'
        },
        {
          label: '车牌号',
          prop: 'plateNumber'
        },
        {
          label: '技术状况',
          prop: 'techStatus',
          slot: 'techStatus'
        },
        {
          label: '厂家编号',
          prop: 'factoryNumber'
        },
        {
          label: '厂家名称',
          prop: 'factoryName'
        },
        {
          label: '出厂时间',
          prop: 'factoryTime',
          slot: 'factoryTime',
          width: '90'
        },
        {
          label: '设计能力',
          prop: 'designAbility'
        },
        {
          label: '购买时间',
          prop: 'payTime',
          slot: 'payTime',
          width: '90'
        },
        {
          label: '机长',
          prop: 'captain'
        },
        {
          label: '外形尺寸',
          prop: 'size'
        },
        {
          label: '发动机编号',
          prop: 'engineNumber',
          width: '100'
        },
        {
          label: '重量',
          prop: 'weight'
        },
        {
          label: '底盘号',
          prop: 'chassisNumber'
        },
        {
          label: '是否监视测量仪器',
          prop: 'monitorDevice',
          slot: 'monitorDevice',
          width: '130'
        },
        {
          label: '是否特种设备',
          prop: 'specialDevice',
          slot: 'specialDevice',
          width: '130'
        },
        {
          label: '是否大型专用设备',
          prop: 'professionalDevice',
          slot: 'professionalDevice',
          width: '130'
        },
        {
          label: '备注',
          prop: 'remark'
        },
        {
          label: '购置原值',
          prop: 'payAmount'
        },
        {
          label: '重置原值',
          prop: 'resetAmount'
        },
        {
          label: '规定折旧月数',
          prop: 'oldMonth',
          width: '130'
        },
        {
          label: '使用月数',
          prop: 'useMonth'
        },
        {
          label: '净值',
          prop: 'netValue'
        },
        {
          label: '残值',
          prop: 'residualValue'
        },
        {
          label: '残值率',
          prop: 'residualRate'
        },
        {
          label: '剩余折旧月数',
          prop: 'remainMonth',
          width: '130'
        },
        {
          label: '累计折旧值',
          prop: 'totalOldValue',
          width: '130'
        },
        {
          label: '辅机名称',
          prop: 'amName'
        },
        {
          label: '辅机型号',
          prop: 'amModel'
        },
        {
          label: '辅机厂家',
          prop: 'amFactory'
        },
        {
          label: '辅机功率',
          prop: 'amPower'
        },
        {
          label: '辅机编号',
          prop: 'amNumber'
        },
        {
          label: '辅机出厂时间',
          prop: 'amTime',
          slot: 'amTime',
          width: '130'
        },
        {
          label: '图片',
          prop: 'image'
        },
        {
          label: '编制时间',
          prop: 'createTime',
          slot: 'createTime',
          width: '90'
        },

        {
          fixed: 'right',
          label: '操作',
          width: '180',
          prop: 'options',
          slot: 'options'
        }
      ]
    }
  },
  computed: {
    canSave() {
      return this.imported && this.dataList.length > 0
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    selectedNode(newValue) {
      this.getTableList(newValue)
    }
  },
  mounted() {
    this.initTree()
  },
  methods: {
    importFile() {
      this.$refs.uploadELe.click()
    },
    downloadFile() {
      saveAs(
        window.location.pathname + '机械设备库导入模板.xls',
        '机械设备库导入模板.xls'
      )
    },
    fileChange(e) {
      const file = e.target.files[0]

      const formData = new FormData()
      formData.append('file', file)
      formData.append('machineDeviceDirectoryId', this.selectedNode.id)
      this.uploadFile(formData)
    },
    uploadFile(formData) {
      this.uploading = true
      importMachineDeviceDetail(formData)
        .then((res) => {
          this.uploading = false
          const { msg, code } = res
          if (code === '0001') {
            this.imported = true
            this.$message.success(msg)
            // 更新列表
            this.getTableList(this.selectedNode)
          } else {
            this.$message.error(msg || '导入失败')
          }
        })
        .catch(() => {
          this.uploading = false
          this.$refs.uploadELe.value = null
        })
    },
    editDir() {
      this.showDirectoryMange = true
    },
    delDir() {
      if (!this.selectedNode) {
        return
      }
      this.$confirm('确定要删除该机械设备目录吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const { id } = this.selectedNode
          deleteMachineDirectory({
            machineDeviceDirectoryId: id
          }).then((res) => {
            const { code, msg } = res
            if (code === '0001') {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.initTree()
            } else {
              this.$message({
                type: 'error',
                message: msg || '删除失败!'
              })
            }
          })
        })
        .catch(() => {})
    },
    dateFormat(data) {
      if (data) {
        return moment(data).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    pageChange(data) {
      this.pageParams.pageNum = data
      this.getTableList(this.selectedNode)
    },
    search() {
      this.pageParams.pageNum = 1
      this.getTableList(this.selectedNode)
    },
    addConsumableLedger() {
      this.optType = 'add'
      this.showModal = true
    },
    editConsumableLedger(data) {
      this.optType = 'edit'
      this.updateMaterialCodeObj = data
      this.showModal = true
    },
    viewDetail(data) {
      this.optType = 'detail'
      this.updateMaterialCodeObj = data
      this.showModal = true
    },
    delConsumableLedger(row) {
      this.$confirm('确定要删除该易耗品台账吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const { id } = row
          deleteMachineDeviceDetail({
            machineDeviceDetailId: id
          }).then((res) => {
            const { code, msg } = res
            if (code === '0001') {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getTableList(this.selectedNode)
            } else {
              this.$message({
                type: 'error',
                message: msg || '删除失败!'
              })
            }
          })
        })
        .catch(() => {})
    },
    // 获取树结构目录
    initTree() {
      getMachineDirectoryTree().then((res) => {
        const { nodes } = res.data || {}
        this.treeData = nodes || []
      })
    },
    // 材料目录相关
    handleNodeClick(val) {
      this.directCurrentNode = val
    },
    // 同级新增 0  下级新增 1
    directAdd(type) {
      this.addDirect.directAddType = type === 0 ? '同级新增' : '下级新增'
      if (!this.directCurrentNode) {
        this.$message({
          type: 'error',
          message: '请选择一个材料目录!'
        })
        return
      }
      this.showAddMaterialDirect = true
    },
    // 删除目录
    directDel() {
      if (!this.directCurrentNode) {
        this.$message({
          type: 'error',
          message: '请选择一个材料目录!'
        })
        return
      }
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.del_Direct()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    del_Direct() {
      const params = {
        machineDeviceDirectoryId: this.directCurrentNode.id
      }
      deleteMachineDirectory(params).then((res) => {
        this.showTipsFn(res, '删除', () => {
          this.showDirectoryMange = false
          this.directCurrentNode = {}
          this.initTree()
        })
      })
    },
    // 确认新增目录
    add_Direct() {
      if (!this.addDirect.name) {
        this.$message({
          type: 'error',
          message: '请输入材料目录!'
        })
        return
      }
      const params = {
        name: this.addDirect.name,
        parentId:
          this.addDirect.directAddType === 0
            ? this.directCurrentNode.parentId
            : this.directCurrentNode.id
      }
      addMachineDirectory(params).then((res) => {
        this.showTipsFn(res, '保存', () => {
          this.showAddMaterialDirect = false
          this.showDirectoryMange = false
          this.directCurrentNode = {}
          this.initTree()
        })
      })
    },
    // 获取表格数据
    getTableList(data) {
      const { id } = data
      if (id) {
        const params = {
          machineDeviceDirectoryId: id,
          pageNum: 1,
          pageSize: 10
        }
        getMachineDeviceDetailList(params).then((res) => {
          if (res.data && res.data.data) {
            this.tableData = res.data.data
          }
        })
      }
    },
    handleCurrentChange(val) {
      this.currentRow = val
      this.currentDefineWork = val
    },
    delMaterial() {
      if (!this.currentRow) {
        this.$message({
          type: 'error',
          message: '请选择一个材料!'
        })
        return
      }
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.del_Material()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    del_Material() {
      const params = {
        materialDetailId: this.currentRow.id
      }
      deleteMachineDeviceDetail(params).then((res) => {
        this.showTipsFn(res, '删除', () => {
          this.getTableList(this.selectedNode)
        })
      })
    },

    // 新增，修改，删除 提示文案
    showTipsFn(res, type, successFn) {
      const { code, msg } = res
      if (code === '0001') {
        this.$message({
          type: 'success',
          message: `${type}成功!`
        })
        if (successFn) {
          successFn()
        }
      } else {
        this.$message({
          type: 'error',
          message: msg || `${type}失败!`
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  height: 100%;
  .content-left,
  .content-right {
    height: 100%;
  }
  .content-left {
    padding-right: 10px;
    border-right: 1px solid #dedede;
    .el-button {
      margin-bottom: 10px;
    }
  }
  .content-right {
    padding-left: 10px;
    .detail {
      height: calc(100% - 40px);
      margin-top: 10px;
      overflow: auto;
    }
  }
  .tree {
    height: calc(100% - 40px);
    padding-top: 10px;
  }
}
</style>
